/** 
*@��Ŀ����: UIBase 
*@�ļ�����: BaseFragment.java 
*@Author: linlin.zou
*@Date: 2014-12-3 
*@Copyright: 2014 www.alipear.com Inc. All rights reserved. 

*ע�⣺�����ݽ������Ϻ�Ѽ���������޹�˾�ڲ����ģ���ֹ��й�Լ�������������ҵĿ�� 
*/
package com.alipear.shopcredit.common.view.wrapper;

import android.view.ViewTreeObserver;

import com.handmark.pulltorefresh.library.PullToRefreshBase;

public abstract class RequestWrapperBase implements PullToRefreshBase.OnRefreshListener2{

    PullToRefreshBase<?> mContentView;
    private boolean mbFirstResume;
    private boolean mbPreDrawed=false;
    private boolean mbNeedPull= false;
    Boolean mbRefreshEnabled;
    Boolean mbLoadMoreEnabled;

    public RequestWrapperBase(PullToRefreshBase<?> contentView, boolean enableRefresh, boolean enableLoadMore) {
        mbFirstResume = true;
        mContentView = contentView;
        mContentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener(){
            @Override
            public boolean onPreDraw() {
                mbPreDrawed = true;
                if (mbNeedPull) {
                    mbNeedPull = false;
                    refreshData();
                }
                return true;
            }
        });
        mbRefreshEnabled = enableRefresh;
        mbLoadMoreEnabled = enableLoadMore;
        mContentView.setOnRefreshListener(this);
    }

    public void setRefreshEnabled(boolean flag) {
        mbRefreshEnabled = flag;
        updateMode();
    }

    public void setLoadMoreEnabled(boolean flag) {
        mbLoadMoreEnabled = flag;
        updateMode();
    }


    private void updateMode() {
        if (mbRefreshEnabled && mbLoadMoreEnabled) {
            mContentView.setMode(PullToRefreshBase.Mode.BOTH);
        }
        else if (mbRefreshEnabled) {
            mContentView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }
        else {
            mContentView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        }
    }

    public PullToRefreshBase<?> getContentView() {
        return mContentView;
    }

    public Boolean getRefreshEnabled() {
        return mbRefreshEnabled;
    }

    public Boolean getLoadMoreEnabled() {
        return mbLoadMoreEnabled;
    }

    public void refreshData() {
        if (mContentView != null) {
            if (mbPreDrawed) {
            	mContentView.onRefreshComplete();
                mContentView.resetCurrentMode();
                mContentView.setRefreshing();
            }
            else {
                mbNeedPull = true;
            }
        }
    }

    public boolean onResume() {
        if (mbFirstResume) {
            mbFirstResume =false;
            refreshData();
            return true;
        }
        return false;
    }

    public void setNeedRefresh() {
        mbFirstResume= true;
    }
}
